// 云函数入口文件
const cloud = require('wx-server-sdk');
//将xml转化为json包
const xml2js = require('xml2js');
//http访问包
var superagent = require('superagent');
//md5加密包
var md5 = require('md5-node');
//requset包
const request = require('request')

//安装xml向json的转化包

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

//*******************************【配置】****************************
const config = {
  BODY: '伐木累-炒酸奶', //商品类型信息
  MCHID: '1513477211', //商户id
  ENV_ID: 'data-0b70e3', // 环境名称
  FUNC_NAME: 'payCallBack', // 支付成功回调云函数
};

/*
 * 生成随机字符串方法
 */
function createNoncestr(length = 32) {
  let chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  let str = "";
  for (let i = 0; i < length; i++) {
    str += chars.substr(randomFrom(0, chars.length - 1), 1)
  }
  return str;
}
//获取指定区间范围随机数，包括lowerValue和upperValue
function randomFrom(lowerValue, upperValue) {
  return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue);
}
//*****************************************************************************

// 云函数入口函数
exports.main = async (event, context) => {

  let openid = event.userInfo.openId; // openid
  let totalFee = event.totalFee; //传入总价
  let outTradeNo = event.outTradeNo; //传入订单号

  const res = await cloud.cloudPay.unifiedOrder({
    "body": config.BODY,
    "outTradeNo": outTradeNo,
    "spbillCreateIp": "127.0.0.1",
    "subMchId": config.MCHID,
    "totalFee": totalFee,
    "envId": config.ENV_ID,
    "functionName": config.FUNC_NAME,
    "tradeType": 'JSAPI',
    "nonceStr": createNoncestr()
  })

  return res

}